package zyb.myproject;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Scanner;

public class GoodsOperateImpl implements GoodsOperator {

	// 商品操作 列出商品
	@Override
	public void listGoods() throws Exception {

		File file = new File("F:\\manager\\goods");

		File[] f = file.listFiles();

		for (int i = 0; i < f.length; i++) {
			FileInputStream fis = new FileInputStream("F:\\manager\\goods\\" + f[i].getName());
			ObjectInputStream ois = new ObjectInputStream(fis);
			Goods goods = (Goods) ois.readObject();
			System.out.println(goods);
			fis.close();
			ois.close();
		}

	}

	// 商品操作 选购商品
	@Override
	public void selectGoods(Cart cart) throws Exception {

		boolean b = true;
		Scanner sc = new Scanner(System.in);
		do {
			System.out.print("请选择商品id进行选购：");
			int id = sc.nextInt();
			System.out.print("选择数量：");
			int num = sc.nextInt();

			File file = new File("F:\\manager\\goods");
			File[] f = file.listFiles();
			int mem = 0;
			for (int i = 0; i < f.length; i++) {
				FileInputStream fis = new FileInputStream("F:\\manager\\goods\\" + f[i].getName());
				ObjectInputStream ois = new ObjectInputStream(fis);
				Goods goods = (Goods) ois.readObject();

				if (goods.getId() == id) {
					cart.addCart(new Goods(goods.getId(), goods.getGoodName(), goods.getPrice(), num));
					System.out.println("恭喜您，添加成功");
				} else {
					mem++;
				}
				if (mem == f.length) {
					System.out.println("抱歉 ，没有这个ID，添加失败");
				}
				fis.close();
				ois.close();
			}
			System.out.println("请问是否继续进行购买：y/n");
			String n = sc.next();
			if ("n".equals(n)) {
				b = false;
			}
		} while (b);

	}

}
